/**
 * @author renbangjie renbangjie@126.com
 * @date 2015-1-27 下午7:01:34
 * @version V1.0
 * <b>Copyright (c)</b> 2014医信金融信息服务（上海）有限公司-版权所有<br/>
 */
package com.yjd.api.user;

import com.yjd.comm.base.control.MobileBaseControl;
import com.yjd.comm.base.service.IMfqTokenService;
import com.yjd.comm.cache.RedisCachUtils;
import com.yjd.comm.device.service.IDeviceService;
import com.yjd.comm.enums.CachNameSpaceEnum;
import com.yjd.comm.system.model.SysParamModel;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.user.dto.UserSession;
import com.yjd.comm.user.model.UserModel;
import com.yjd.comm.user.service.IUserService;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.UserAccessTokenUtil;
import com.yjd.comm.vo.Constant.SysParamKeyEnum;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 注册(用户注册)
 *
 * @author wap
 */
@Controller
@Scope("prototype")
@RequestMapping("/reg/")
public class RegisterControl extends MobileBaseControl {

    private final Logger logger = LoggerFactory.getLogger(RegisterControl.class);

    @Resource
    private IUserService userService;

    @Resource
    private IDeviceService deviceService;


    @Resource
    private IMfqTokenService mfqTokenService;

    /**
     * 注册第一步（获取短信验证码）
     *
     * @param phonenumber
     * @throws Exception void
     */
    @RequestMapping(value = "step/0", method = RequestMethod.POST)
    public void msg(@RequestParam(required = false) String phonenumber) throws Exception {
        if (validMobileNumber(phonenumber)) {
            super.sendMessage(phonenumber);
        }
    }

    /**
     * 新版，注册第一步（获取短信验证码）
     *
     * @param phonenumber
     * @throws Exception void
     */
    @RequestMapping(value = "step/0/v4", method = RequestMethod.POST)
    public void getMsg(@RequestParam(required = false) String phonenumber, String imageCodeId, String code) throws Exception {
        if(!ServletUtil.validateImageCode(imageCodeId, code)){
           this.errorMsg("验证码无效或者过期，请重新获取。");
           return;
        }
        if (validMobileNumber(phonenumber)) {
            super.sendMessage(phonenumber);
        }
    }

    /**
     * 注册第二步,校验短信验证码
     *
     * @param phonenumber
     * @param msgCode
     * @throws Exception
     */
    @RequestMapping(value = "step/1", method = RequestMethod.POST)
    public void step1(@RequestParam(required = false) String phonenumber, @RequestParam(required = false) String msgCode) throws Exception {
        if (validMobileNumber(phonenumber)) {
            if (StringUtils.isBlank(msgCode)) {
                this.errorMsg("请输入验证码");
                return;
            }
            if (!super.compareMessageCode(phonenumber, msgCode)) {
                this.errorMsg("验证码无效或已过期");
                return;
            }
            String uuid = UUID.randomUUID().toString();
            RedisCachUtils.putCach(CachNameSpaceEnum.VALIDATE_MSG_TOKEN,phonenumber,uuid);
            this.successData(FrameUtil.newHashMap("message", "验证通过", "valid_token", uuid));
        }
    }

    /**
     * 注册第三步，设置用户登录密码
     * phonenumber  手机号
     * password  短信验证码
     * device_no 设备号
     * mobile_type 手机类型  android、ios
     * regid 极光推送id
     * valid_token  验证token 前一步
     * @throws Exception
     */
    @RequestMapping(value = "step/2", method = RequestMethod.POST)
    public void step2(@RequestParam(required = false) String phonenumber, @RequestParam(required = false) String password,
                      @RequestParam(required = false) String device_no, @RequestParam(required = false) String mobile_type,
                      @RequestParam(required = false) String regid, @RequestParam(required = false) String valid_token) throws Exception {

        // 校验手机
        if (!validMobileNumber(phonenumber)) {
            return;
        }

        if (StringUtils.isBlank(password) || StringUtils.isBlank(mobile_type) || StringUtils.isBlank(valid_token)) {
            FrameUtil.throwBaseException1("参数异常");
        }
        //获取缓存中的token
        String v_token =  RedisCachUtils.getCachValueOfString(CachNameSpaceEnum.VALIDATE_MSG_TOKEN,phonenumber);
        if(!valid_token.equals(v_token)){
            this.errorMsg("请求不合法,请重新获取短信验证码！");
            return;
        }
        RedisCachUtils.delCach(CachNameSpaceEnum.VALIDATE_MSG_TOKEN,phonenumber);//删除已经验证通过的缓
        UserModel uModel = userService.regModel(password.toLowerCase(), phonenumber, device_no, mobile_type, regid, ServletUtil.getIpAddr(request));

        if (uModel == null) {
            this.errorMsg("系统繁忙,请稍后再试");
            return;
        }
        Long idUser = uModel.getUser_id();
        // 查询用户详细信息
        UserSession mUser = deviceService.getMobileUser(idUser);
        if (mUser == null) {
            this.errorMsg("系统繁忙,请稍后再试");
            return;
        }
        String token = UserAccessTokenUtil.generateAccessToken(mUser);
        this.successData(FrameUtil.newHashMap("access_token", token, "user_id", mUser.getUser_id(), "mobile", mUser.getMobile_number()));
    }

    /**
     * 验证手机号
     *
     * @param mphoneNo 手机号码
     * @return boolean
     * @throws Exception
     */
    protected boolean validMobileNumber(String mphoneNo) throws Exception {
        if (StringUtils.isBlank(mphoneNo)) {
            super.errorMsg("请输入手机号码!");
            return false;
        }

        if (!NumberUtils.isNumber(mphoneNo)) {
            super.errorMsg("请输入正确的手机号哟!");
            return false;
        }

        // 正则验证
        SysParamModel sysParamModel = SysParamUtil
                .getSysParamModel(SysParamKeyEnum.REGISTER_REGEX);
        if (sysParamModel != null) {
            Matcher name = Pattern.compile(sysParamModel.getParam_value())
                    .matcher(mphoneNo);
            if (!name.matches()) {
                super.errorMsg("请输入正确的手机号哟!");
                return false;
            }
        }

        // 是否已经被使用了
        if (userService.mobileIsExits(mphoneNo)) {
            super.errorMsg("该手机号码已被注册!");
            return false;
        }
        return true;
    }

    @RequestMapping("user/protocol")
    public String protocol() throws Exception {
        return "reg/userProtocol";
    }

    @RequestMapping("pf/protocol")
    public String agreement() throws Exception {
        return "reg/pfProtocol";
    }
}
